package com.xiaoer.core.net

import android.content.Context
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author wangzw
 * @data 2023/7/27
 */
class RetrofitUtils {
    companion object {
        private lateinit var retrofit: Retrofit
        fun <T> getController(tClass: Class<T>, context: Context): T {
            if (!this::retrofit.isInitialized) {
                updateController()
            }
            return retrofit.create(tClass);
        }

        fun updateController() {
            synchronized(RetrofitUtils::class.java) {
                val logging = HttpLoggingInterceptor();
                logging.setLevel(HttpLoggingInterceptor.Level.BODY);

                var httpClient = OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)

                httpClient.addInterceptor(logging)
                retrofit = Retrofit.Builder()
                    .baseUrl("https://api.cntv.cn/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build();
            }
        }
    }
}